package jwei.apps.indextank.service;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.util.Log;

public class GeocoderService {

    public static Location geocode(String address, Context context) {
        Location location = new Location("reverseGeocoded");

        if (address != null) {
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());
            try {
                List<Address> addressResult = geocoder.getFromLocationName(address, 1);
                if (!addressResult.isEmpty()) {
                    Address resultAddress = addressResult.get(0);
                    location.setLatitude(resultAddress.getLatitude());
                    location.setLongitude(resultAddress.getLongitude());
                }
            } catch (IOException e) {
                Log.d("Contact Location Lookup Failed", e.getMessage());
                location = null;
            }
        }

        return location;
    }

    public static String reverseGeocode(Location location, Context context) {

        String myAddress = "No address found";

        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();

            Geocoder gc = new Geocoder(context, Locale.getDefault());
            try {
                List<Address> addresses = gc.getFromLocation(lat, lng, 1);
                StringBuilder sb = new StringBuilder();
                if (addresses.size() > 0) {
                    Address address = addresses.get(0);
                    sb.append(address.getAddressLine(0) + ", ");
                    sb.append(address.getAddressLine(1));
                }
                myAddress = sb.toString();
            } catch (IOException e) {
            }
        }

        return myAddress;
    }

}
